package com.zyn.es.basic;

import java.util.HashMap;
import java.util.Map;

import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;

/**
 * 批量操作
 * 
 * https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-docs-bulk.html
 * 
 * @author tongyufu
 *
 */
public class BulkAPI extends EsClient {

    public static void main(String[] args) {
        new BulkAPI().bulkIndex();
    }

    public void bulkIndex() {
        super.initClient();
        log.info("================================");
        BulkRequestBuilder build = client.prepareBulk();

        Map<String, Object> json = new HashMap<String, Object>();
        json.put("title", "title 10");
        json.put("content", "Version 5.0 released today!");
        json.put("priority", 10);
        json.put("tags", new String[] { "announce", "elasticsearch", "release" });
        build.add(client.prepareIndex(INDEX, TYPE, "10").setSource(json));

        json.put("title", "title 11");
        json.put("content", "Version 5.0 released today!");
        json.put("priority", 10);
        json.put("tags", new String[] { "announce", "elasticsearch", "release" });
        build.add(client.prepareIndex(INDEX, TYPE, "11").setSource(json));

        BulkResponse responses = build.get();
        if (responses.hasFailures()) {
            for (BulkItemResponse item : responses) {
                if (item.isFailed()) {
                    log.info(item.getFailureMessage());
                }
            }
        }
        client.close();
        log.info("================================");
    }
}
